import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import type { Users } from '@/types/loginType'

export const useUserStore = defineStore('useUserStore', () => {
  const usersOrigin = ref<Users[]>([])
  const users = ref<Users[]>([])
  const pageTotal = ref(0)

  function select(key: string) {
    if (!key) {
      // key 为空
      assignUsers(1)
    } else {
      users.value = usersOrigin.value.filter((item) => item.id === key || item.name === key)
      pageTotal.value = users.value.length
    }
  }
  // 获取数据
  async function getFollowigUsers(id: string) {
    const { searchFollowigUsers } = useAsyncAxios()
    const { status, data } = await searchFollowigUsers(id)
    if (status === 200) {
      pageTotal.value = (data as Users[]).length
      return { status, data }
    } else {
      pageTotal.value = usersOrigin.value.length
      return { status, data }
    }
  }
  // 修改方法
  function assignUsersOrigin(data: Users[]) {
    usersOrigin.value = data
  }
  function assignUsers(page: number) {
    // 换页读取
    if (page === 1) {
      const start = 0
      const end = 50
      users.value = usersOrigin.value.slice(start, end)
    } else {
      const start = (page - 1) * 50
      const end = page * 50
      users.value = usersOrigin.value.slice(start, end)
    }
  }
  return {
    usersOrigin,
    users,
    pageTotal,
    select,
    assignUsersOrigin,
    assignUsers,
    getFollowigUsers
  }
})
